/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.amap.AmapUtils;
import com.rzico.basics.entity.*;
import com.rzico.basics.model.CardView;
import com.rzico.basics.service.*;
import com.rzico.core.entity.*;
import com.rzico.core.service.SysEmployeeService;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysOfficeService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 会员控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "会员接口")
@RestController
@RequestMapping("/admin/member")
public class MemberAdminController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MemberService memberService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysEmployeeService sysEmployeeService;

    @Autowired
    private SysMchService sysMchService;

    @Autowired
    private SysOfficeService sysOfficeService;

    @Autowired
    private ReceiverService receiverService;

    @Autowired
    private ShopService shopService;

    @Autowired @Lazy
    private CardService cardService;

    @Autowired
    private VipService vipService;

    @Autowired
    private AmapUtils amapUtils;


    /**
     * 客户统计
     *
     * @return
     */
    @ApiOperation("客户统计")
    @GetMapping("/summary")
    @ApiImplicitParams({@ApiImplicitParam(name = "days", value = "统计天数0为当前，近7天为6", dataType = "Integer", allowMultiple = true, paramType = "query")})
    public CommResult<SysPvuvTravel> summary(Integer days) {
        Map<String, Object> params = new HashMap<String, Object>();
        Enterprise enterprise = enterpriseService.getCurrent();
        params.put("enterpriseId", enterprise.getId());
        params.put("startDate", DateUtils.truncate(DateUtils.addDays(new Date(),-days), Calendar.DATE));
        params.put("endDate", new Date());

        List<Map<String,Object>> data = memberService.summary(params);
        return CommResult.success(data);
    }


    /**
     * 分页查询会员
     *
     * @return
    */
    @ApiOperation("分页查询会员")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "memberCategoryId", value = "客户分类", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "客户名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "地址", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "联系电话", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "vipId", value = "等级ID", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "综合搜索", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "deleted", value = "是否删除", dataType = "String", paramType = "query")
    })
    public CommResult<Member> list(String startDate, String endDate,Long  memberCategoryId,Long vipId,String name,String keyword,String address,String phone,Boolean deleted, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(startDate)){
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)){
            params.put("endDate", endDate);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (sysMch.getMchType().equals(3)) {
            params.put("mchId", enterprise.getMchId());
        } else
        if (sysMch.getMchType().equals(0)) {
            params.put("mchId", enterprise.getMchId());
        } else {
            params.put("enterpriseId", enterprise.getId());
//      非管理员都启用数据权限 暂不启用
//            SysUser sysUser = sysUserService.getCurrent();
//            if (!sysUserService.isAdmin(sysUser)) {
//                params.put("dataScopeId",sysUser.getId());
//            }
        }

        if (name!=null) {
            params.put("name",name);
        }

        if (address!=null) {
            params.put("address",address);
        }

        if (vipId!=null) {
            Vip vip = vipService.selectByPrimaryKey(vipId);
            if (vip.getMethod().equals(3)) {
                params.put("supperVip",vip.getVip());
                params.put("vipExpired",new Date());
            } else {
                params.put("vip",vip.getVip());
            }
        }

        if (memberCategoryId!=null) {
            if (memberCategoryId==0L) {
                params.put("memberCategoryId", memberCategoryId);
            } else {
                params.put("treePath", String.valueOf(memberCategoryId));
            }
        }

        if (keyword!=null && !"".equals(keyword)) {
            params.put("keyword",keyword);
        }

        if (phone!=null) {
            params.put("phone",phone);
        }

        if (deleted!=null) {
            params.put("deleted",deleted);
        } else {
            params.put("deleted", false);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Member> list = memberService.selectList(params);
        PageResult<Member> pageResult = new PageResult<Member>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }

    /**
     * 查询单条会员
     *
     * @return
    */
    @ApiOperation("查询单条会员")
    @GetMapping("/find/{id}")
    public CommResult<Member> find(@PathVariable String id) {
        Member result = memberService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("member",result);

        data.put("freezeBalance",result.getFreezeBalance());
        data.put("balance",result.getBalance());
        data.put("point",result.getPoint());
        data.put("freezePoint",result.getFreezePoint());

        data.put("promoterName","无");
        if (result.getPromoterId()!=null) {
            Member promoter = memberService.selectByPrimaryKey(result.getPromoterId());
            if (promoter!=null) {
                data.put("promoterName",promoter.getName());
            }
        }

        if (result.getOfficeId()!=null && !"".equals(result.getOfficeId())) {
            SysOffice sysOffice = sysOfficeService.selectByPrimaryKey(result.getOfficeId());
            if (sysOffice!=null) {
                data.put("officeName", sysOffice.getName());
            } else {
                data.put("officeName", "无");
            }
        } else {
            data.put("officeName", "无");
        }


        if (result.getShopId()!=null) {
            Shop shop = shopService.selectByPrimaryKey(result.getShopId());
            if (shop!=null) {
                data.put("shopName", shop.getName());
            } else {
                data.put("shopName", "无");
            }
        } else {
            data.put("shopName", "无");
        }


        return CommResult.success(data);

    }

    /**
     * 保存会员
     *
     * @param member
     * @return
     */
    @ApiOperation("保存会员")
    @PostMapping("/save")
    @ApiImplicitParams({@ApiImplicitParam(name = "building", value = "所在小区/大楼", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "roomNumber", value = "门店号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "consignee", value = "收货人", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "address", value = "详情地址", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "lat", value = "lat", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "lng", value = "lng", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "level", value = "楼层(0.有电梯,1-9楼）", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isDefault", value = "是否默认", dataType = "Boolean", paramType = "query")
    })
    public CommResult<Member> save(@RequestBody Member member,String building,String roomNumber,String consignee,String phone,String address,Double lat,Double lng,Integer level,Boolean isDefault) {

        Enterprise enterprise = enterpriseService.getCurrent();

        String mchId = enterprise.getMchId();
        SysMch sysMch = sysMchService.selectByPrimaryKey(mchId);
        if (sysMch.getMchType().equals(1) || sysMch.getMchType().equals(2)) {
            mchId = sysMchService.getIsvId(sysMch);
        }

        Member existMember = memberService.findByMchMobile(mchId,member.getMobile());
        if (existMember!=null) {
            if (existMember.getDeleted()) {
                member.setId(existMember.getId());
            } else {
                return CommResult.error("客户已经存在");
            }
        }

        if (member.getCode()!=null && !"".equals(member.getCode())) {
            Member codeMember = memberService.findByCode(mchId, member.getCode());
            if (codeMember != null && !codeMember.getId().equals(member.getId())) {
                return CommResult.error("客户编号重复");
            }
        }

        Shop shop = shopService.findByPoint(enterprise,0d,0d);
        if (shop!=null) {
            member.setShopId(shop.getId());
            member.setShopName(shop.getName());
        }
        member.setEnterpriseId(enterprise.getId());
        member.setMchId(mchId);
        if (member.getId()==null) {
            memberService.createMember(member);
        } else {
            if (member.getUserId()==null) {
                memberService.updateByPrimaryKeySelective(member);
            } else {
                member.setDeleted(false);
                member = memberService.update(member);
                if (member == null){
                    return CommResult.error();
                }
            }
        }

        Receiver receiver = new Receiver();
        receiver.setCreateDate(new Date());
        receiver.setLat(lat);
        receiver.setLng(lng);
        receiver.setPhone(phone);
        receiver.setConsignee(consignee);
        receiver.setAddress(address);
        receiver.setMemberId(member.getId());
        receiver.setBuilding(building);
        receiver.setRoomNumber(roomNumber);
        receiver.setIsDefault(true);
        receiver.setLevel(level);
        if (receiver.getLat()!=null && receiver.getLng()!=null && receiver.getLat()>0 && receiver.getLng()>0) {
            Map<String, Object> data = amapUtils.geoCode(receiver.getLat(), receiver.getLng());
            if (data.containsKey("areaId")) {
                receiver.setAreaId(Integer.parseInt(data.get("areaId").toString()));
            }
            if (data.containsKey("areaName")) {
                receiver.setAreaName(data.get("areaName").toString());
            }
        }
        int affectCount = receiverService.save(receiver);
        if (affectCount <= 0) {
            return CommResult.error();
        }

        Member result = memberService.findById(member.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除会员
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除会员", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除会员,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Member> del(@PathVariable String ids) {

        memberService.deleteByIds(ids.split(","));
        return CommResult.success();

    }


    /**
     * 更新会员
     *
     * @param member
     * @return
     */
    @Log(desc = "更新会员", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新会员")
    @PostMapping("/updateMember")
    public CommResult<Member> updateMember(@RequestBody Member member) {
        int affectCount = memberService.updateByPrimaryKeySelective(member);
        if (affectCount <= 0) {
            return CommResult.error();
        }

        Member result = memberService.findById(member.getId());
        return CommResult.success(result);

    }

    /**
     * 更新会员
     *
     * @param member
     * @return
     */
    @Log(desc = "更新会员", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新会员")
    @PostMapping("/update")
    public CommResult<Member> update(@RequestBody Member member) {

        Enterprise enterprise = enterpriseService.getCurrent();


        String mchId = enterprise.getMchId();
        SysMch sysMch = sysMchService.selectByPrimaryKey(mchId);
        if (sysMch.getMchType().equals(1) || sysMch.getMchType().equals(2)) {
            mchId = sysMchService.getIsvId(sysMch);
        }

        if (member.getCode()!=null) {
            Member codeMember = memberService.findByCode(mchId, member.getCode());
            if (codeMember != null && !codeMember.getId().equals(member.getId())) {
                return CommResult.error("编号重复");
            }
        } else {
            if (member.getCode() == null || "".equals(member.getCode())) {
                member.setCode(memberService.getMaxCode(member.getMchId()));
            }
        }

        Member existMember = memberService.findById(member.getId());
        if (existMember.getMobile()!=null && member.getMobile()!=null) {
            existMember = memberService.findByMchMobile(mchId, member.getMobile());
            if (existMember != null) {
                if (!existMember.getId().equals(member.getId())) {
                    return CommResult.error("客户已经存在");
                }
            }
        }

        //不可被更新的字段
        member.setBalance(null);
        member.setFreezeBalance(null);
        member.setPoint(null);
        member.setMchId(null);
        member.setEnterpriseId(null);
        if (member.getUserId()==null) {
            memberService.updateByPrimaryKeySelective(member);
        } else {
            member = memberService.update(member);
            if (member == null){
                return CommResult.error();
            }
        }
        return CommResult.success(member);

    }



    /**
     * 客户过户
     *
     * @param memberId
     * @return
     */
    @Log(desc = "客户过户", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("客户过户")
    @PostMapping("/transfer")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "mchId", value = "商户ID", dataType = "String", paramType = "query")
    })
    public CommResult<Member> transfer(Long memberId,String mchId) {
        Enterprise enterprise = enterpriseService.findByMch(mchId);
        Member member = memberService.findById(memberId);

        if (member.getBalance().compareTo(BigDecimal.ZERO)>0) {
            return CommResult.error("账户存在余额不能过户");
        }

        if (member.getPoint()>0L) {
            return CommResult.error("账户存在金币不能过户");
        }

        if (member.getMatchPoint()>0L) {
            return CommResult.error("账户存在积分不能过户");
        }

        CardView cardView = cardService.summary(member.getId());
        if (cardView!=null) {
            if (cardView.getBalance().compareTo(BigDecimal.ZERO) > 0) {
                return CommResult.error("会员卡有余额不能过户");
            }
            if (cardView.getBenefits().compareTo(BigDecimal.ZERO) > 0) {
                return CommResult.error("福利卡有余额不能过户");
            }
        }

        //TODO

        Shop shop = shopService.findByPoint(enterprise,0d,0d);
        if (shop==null) {
            return CommResult.error("没有开通门店");
        }

        memberService.moveTo(member,shop);

        return CommResult.success(member);

    }

    @ApiOperation("获取登录会员信息")
    @GetMapping(value = "/getInfo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员ID", dataType = "Long", paramType = "query")
    })
    public CommResult<Member> getInfo(Long memberId,HttpServletRequest request) {
        CommResult commResult = new CommResult();
        Member member = memberService.getCurrent();
        if (memberId!=null) {
            member = memberService.selectByPrimaryKey(memberId);
        }
        Map<String, Object> data = new HashMap<>();
        if (member!=null) {
            data.put("member",member);
        }

        if (memberId!=null) {
            data.put("freezeBalance", member.getFreezeBalance());
            data.put("balance", member.getBalance());
            data.put("point", member.getPoint());
            data.put("freezePoint", member.getFreezePoint());
        }
        commResult.setData(data);
        return commResult;
    }


    @ApiOperation("绑定员工账号")
    @GetMapping(value = "/bindEmployee")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "employeeId", value = "员工ID", dataType = "String", paramType = "query")
    })
    public CommResult<Member> bindEmployee(Long memberId,String employeeId,HttpServletRequest request) {
        Member member = memberService.findById(memberId);
        SysEmployee sysEmployee = sysEmployeeService.selectByPrimaryKey(employeeId);
        if (sysEmployee==null) {
            return CommResult.error("无效员工号");
        }
        if (member==null) {
            return CommResult.error("无效会员号");
        }
        sysEmployee.setMemberId(memberId);
        sysEmployeeService.updateByPrimaryKeySelective(sysEmployee);
        return CommResult.error("绑定成功");
    }

    /**
     * 查询会员推广的会员
     *
     * @return
     */
    @ApiOperation("查询会员推广的会员")
    @GetMapping("/memberList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "memberId", value = "会员ID", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "状态(0.未成交,1.已成交)", dataType = "String", paramType = "query")
    })
    public CommResult<Member> memberList(Long memberId,Integer status, Pageable pageable) {

        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);

        Member member = memberService.selectByPrimaryKey(memberId);
        params.put("promoterId", member.getId());

        if (status!=null) {
            params.put("status",status);
        }

        params.put("deleted", false);

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Member> list = memberService.selectList(params);
        PageResult<Member> pageResult = new PageResult<Member>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);

    }


}
